import React from 'react'
import { Card, Form, Input, Switch, Button, message, Tabs, InputNumber } from 'antd'
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
import { getRateLimitConfig, updateRateLimitConfig } from '../api/gateway'

export default function RateLimitConfig() {
  const [form] = Form.useForm()
  const queryClient = useQueryClient()

  const { data: config, isLoading } = useQuery({
    queryKey: ['rateLimitConfig'],
    queryFn: getRateLimitConfig,
  })

  // 当数据加载成功后设置表单值
  React.useEffect(() => {
    if (config) {
      form.setFieldsValue(config)
    }
  }, [config, form])

  const updateMutation = useMutation({
    mutationFn: updateRateLimitConfig,
    onSuccess: () => {
      message.success('配置更新成功')
      queryClient.invalidateQueries({ queryKey: ['rateLimitConfig'] })
    },
    onError: () => {
      message.error('配置更新失败')
    },
  })

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields()
      updateMutation.mutate(values)
    } catch (error) {
      console.error('Validation failed:', error)
    }
  }

  if (isLoading) {
    return <div>加载中...</div>
  }

  return (
    <div>
      <h1 style={{ marginBottom: '24px' }}>限流配置</h1>
      <Card>
        <Form form={form} layout="vertical" style={{ maxWidth: 800 }}>
          <Form.Item name="enabled" valuePropName="checked">
            <Switch checkedChildren="启用限流" unCheckedChildren="禁用限流" />
          </Form.Item>
          <Form.Item name="strategy" label="限流策略">
            <Input placeholder="token_bucket 或 leaky_bucket" />
          </Form.Item>
          <Tabs>
            <Tabs.TabPane tab="全局限流" key="global">
              <Form.Item name={['global', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
              <Form.Item name={['global', 'qps']} label="QPS（每秒请求数）">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name={['global', 'burst']} label="突发流量">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Tabs.TabPane>
            <Tabs.TabPane tab="IP 限流" key="per_ip">
              <Form.Item name={['per_ip', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
              <Form.Item name={['per_ip', 'qps']} label="QPS（每秒请求数）">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name={['per_ip', 'burst']} label="突发流量">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Tabs.TabPane>
            <Tabs.TabPane tab="用户限流" key="per_user">
              <Form.Item name={['per_user', 'enabled']} valuePropName="checked">
                <Switch checkedChildren="启用" unCheckedChildren="禁用" />
              </Form.Item>
              <Form.Item name={['per_user', 'qps']} label="QPS（每秒请求数）">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
              <Form.Item name={['per_user', 'burst']} label="突发流量">
                <InputNumber min={1} style={{ width: '100%' }} />
              </Form.Item>
            </Tabs.TabPane>
          </Tabs>
          <Button
            type="primary"
            onClick={handleSubmit}
            loading={updateMutation.isLoading}
            style={{ marginTop: 16 }}
          >
            保存配置
          </Button>
        </Form>
      </Card>
    </div>
  )
}

